package com.zhj.bz.algorithm.sort.swap;

import com.zhj.tool.CallBack;
import com.zhj.tool.TimeTools;

/**
 * @author zhj
 */
public class BubbleSort {

    public static void main(String[] args) {
        int[] arr = {-5, -1,  2, 9, 10};

        sort(arr);
        sortPlus(arr);
        int[] bigArr = new int[80000];
        for (int i = 0; i < 80000; i++) {
            bigArr[i] = (int) (Math.random() * 80000);
        }
        System.out.println("冒泡排序：");
        TimeTools.useTime(new CallBack(){
            //定义execute方法
            public void execute(){
                sort(bigArr);
            }
        });
        for (int i = 0; i < 80000; i++) {
            bigArr[i] = (int) (Math.random() * 80000);
        }
        System.out.println("优化冒泡排序：");
        TimeTools.useTime(new CallBack(){
            //定义execute方法
            public void execute(){
                sortPlus(bigArr);
            }
        });
    }

    /**
     * 冒泡排序
     * @param arr
     */
    public static void sort(int [] arr) {
        int temp = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j]) {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
                // System.out.print("执行比较\t");
            }
            // System.out.println("第" + (i+1) + "次排序的结果：" + Arrays.toString(arr));
        }
    }

    /**
     * 优化过的冒泡顺序对，就不会继续比较
     * @param arr
     */
    public static void sortPlus(int [] arr) {
        int temp = 0;
        boolean flag = false;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j]) {
                    flag = true;
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
                // System.out.print("执行比较\t");
            }
            if (!flag) {
                break;
            }
            flag = false;
            // System.out.println("第" + (i+1) + "次排序的结果：" + Arrays.toString(arr));
        }
    }
}
